/**
 *  Copyright Matt Silbernagel 2010
 *  
 *	This file is part of MobilePrinting.
 *
 *	MobilePrinting is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MobilePrinting is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MobilePrinting.  If not, see <http://www.gnu.org/licenses/>.
 */

package edu.uc.labs.MobilePrinting.Fetch;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import static edu.uc.labs.MobilePrinting.Configurator.*;


/**
 * 
 * Sends a GET request to a server and receives and writes text file that
 * becomes the PPD file to use for printer installation
 * 
 */
public class PPDFetcher {

	private String server, zone, queue, os;
	private String input = "";
	private URL u;
	private URLConnection conn;


	public PPDFetcher(String server, String zone, String queue, String osname) {

		this.server = server;
		this.zone = zone;
		this.queue = queue;
		this.os = osname;

		try {
			u = new URL(buildUrl());
		} catch (MalformedURLException ex) {
			LOGGER.error(ex.toString());
		}
		connect();
	}

	private String buildUrl() {
		String url = "http://" + this.server + "/ppd/" + this.zone + "/"
				+ this.os.toLowerCase() + "/" + this.queue + ".ppd";
		LOGGER.debug("The url to fetch the ppd: " + url);
		return url;

	}

	public void connect() {
		try {
			conn = u.openConnection();
			InputStream instream = conn.getInputStream();
			Scanner in = new Scanner(instream);
			while (in.hasNextLine()) {
				input += in.nextLine() + "\n";
			}
		} catch (IOException ex) {
			LOGGER.error(ex.toString());
		}

	}

	public void writeToFile() {
		try {

			// If the directory doesn't exist, create it...
			File theDir = new File(PPD + DELIM + this.zone);
			if (!theDir.exists()) {
				LOGGER.debug(theDir.getAbsolutePath() + " is gonna be created");
				theDir.mkdir();
			}

			// Then write the .ppd file...
			String file_name = PPD + DELIM + this.zone + DELIM + this.queue + ".ppd";
			FileWriter fstream = new FileWriter(file_name);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(input);
			out.close();
		} catch (IOException ex) {
			LOGGER.error(ex);
		}

	}

}
